from flask import request
from flask_login import current_user, login_required
from smartcab import perm
from smartcab.data import db
from .blueprint import hub_bp
from smartcab.data.hub import Hub


@hub_bp.route("/", methods=["POST"])
def register():
    # TODO
    return {"status": "unimplemented"}


@hub_bp.route("/<uuid>", methods=["DELETE"])
@login_required
def unlink(uuid):
    if not current_user.has_perm(perm.ATOMIC_PERMS["unlink_hubs"]):
        return {"status": "error", "error": "low_perms"}

    with db.session() as db_sess:
        hub = db_sess.query(Hub).get(uuid)
        if not hub:
            return {"status": "error", "error": "unknown_hub"}
        db_sess.delete(hub)
        db_sess.commit()

    return {"status": "success"}


@hub_bp.route("/<uuid>", methods=["GET"])
@login_required
def get(uuid):
    if not current_user.has_perm(perm.ATOMIC_PERMS["list_hubs"]):
        return {"status": "error", "error": "low_perms"}

    with db.session() as db_sess:
        hub = db_sess.query(Hub).get(uuid)
        if not hub:
            return {"status": "error", "error": "unknown_hub"}
        return {
            "id": hub.id,
            "addr": hub.addr,
            "pubkey": hub.pubkey,
            "name": hub.name,
            "config": hub.config,
            "version": hub.version,
            "latest_update": hub.latest_update,
        }


@hub_bp.route("/", methods=["GET"])
@login_required
def list():
    if not current_user.has_perm(perm.ATOMIC_PERMS["list_hubs"]):
        return {"status": "error", "error": "low_perms"}

    with db.session() as db_sess:
        hubs = db_sess.query(Hub).order_by(Hub.latest_update.desc()).all()
        response = {"status": "success", "hubs": []}
        for hub in hubs:
            response["hubs"].append(
                {
                    "id": hub.id,
                    "addr": hub.addr,
                    "pubkey": hub.pubkey,
                    "name": hub.name,
                    "config": hub.config,
                    "version": hub.version,
                    "latest_update": hub.latest_update,
                }
            )
        return response


@hub_bp.route("/<uuid>/edit", methods=["POST"])
@login_required
def edit(uuid):
    if not current_user.has_perm(perm.ATOMIC_PERMS["edit_hubs"]):
        return {"status": "error", "error": "low_perms"}

    with db.session() as db_sess:
        hub = db_sess.query(Hub).get(uuid)
        if not hub:
            return {"status": "error", "error": "unknown_hub"}
        hub.addr = request.args.get("addr", hub.addr)
        hub.pubkey = request.args.get("pubkey", hub.pubkey)
        hub.name = request.args.get("name", hub.pubkey)
        hub.config = request.args.get("config", hub.pubkey)
        db_sess.commit()

    return {"status": "success"}
